package com.bondar.task4;

import java.util.Random;

public class PrintCircularOrder extends Thread {
	private PrintCircularOrder nextTask;
	private boolean start;
	final int threadNumber;

	public PrintCircularOrder(int threadNumber, boolean isStarted) {
		super("Thread " + threadNumber);
		
		this.threadNumber = threadNumber;
		this.start = isStarted;
		
//		System.out.println(getName() + " created");
	}
	
	public void setNextTask(PrintCircularOrder nextTask) {
//		System.out.println(getName() + " -> " + nextTask.getName());
		this.nextTask = nextTask;
	}

	public synchronized void setStart(boolean isStarted) {
		this.start = isStarted;
	}


	@Override
	public void run() {
//		System.out.println(getName() + " started");
		while ( !isInterrupted() ) {
			try {
				waitForTurn();
			} catch (InterruptedException e) {
				System.exit(0);
			}
			
			doWork( new Random().nextInt(1_000) );
		}
	}

	private synchronized void waitForTurn() throws InterruptedException {
		while (!start) {	wait();	}	// release lock
	}

	private void doWork(int timeToSleep) {
		
		synchronized (nextTask) {	
			try {
				System.out.println(threadNumber);
				sleep(timeToSleep);
				
			} catch (InterruptedException e) {}
			
			setStart(false);
			nextTask.setStart(true);
			nextTask.notify();			// wake up next thread
		}
	}
}
